package com.retrozelda.nyanimals;

import android.opengl.GLSurfaceView;
import android.opengl.GLES20;
import android.util.Log;
import android.view.MotionEvent;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

public class CNyanimalGLRender implements GLSurfaceView.Renderer
{
	private static final String TAG = CNyanimalGLRender.class.getSimpleName();
	
	private NyanimalGLSurfaceView m_glSurface;
	
	public void SetSurface(NyanimalGLSurfaceView surface)
	{
		m_glSurface = surface;
	}
	
	private CNyanimalGame m_game; // the main game class
	
	public boolean ShouldExit()
	{
		return m_game.ShouldExit();
	}

	@Override
	public void onDrawFrame(GL10 glUnused)
	{
		//CNyanimalGame.GetInstance().Update();
		m_game.Update();
		m_game.Render(m_glSurface);
	}

	@Override
	public void onSurfaceChanged(GL10 glUnused, int width, int height)
	{
		m_game.onSurfaceChanged(width, height);
	}

	@Override
	public void onSurfaceCreated(GL10 glUnused, EGLConfig config)
	{
		Log.d(TAG, "surfaceCreated Start");
		// enable backface culling
		// GLES20.glEnable(GLES20.GL_CULL_FACE);
		// setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);
		GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA);
		GLES20.glEnable(GLES20.GL_BLEND);
		
		// create the game
		m_game = new CNyanimalGame();
		m_game.Init(m_glSurface);

		Log.d(TAG, "surfaceCreated End");
	}

	public static int loadShader(int shaderType, String source)
	{
		int shader = GLES20.glCreateShader(shaderType);
		if (shader != 0)
		{
			GLES20.glShaderSource(shader, source);
			GLES20.glCompileShader(shader);
			int[] compiled = new int[1];
			GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compiled, 0);
			if (compiled[0] == 0)
			{
				Log.e(TAG, "Could not compile shader " + shaderType + ":");
				Log.e(TAG, GLES20.glGetShaderInfoLog(shader));
				GLES20.glDeleteShader(shader);
				shader = 0;
			}
		}
		return shader;
	}

	public static int createProgram(String vertexSource, String fragmentSource)
	{
		int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexSource);
		if (vertexShader == 0)
		{
			return 0;
		}

		int pixelShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentSource);
		if (pixelShader == 0)
		{
			return 0;
		}

		int program = GLES20.glCreateProgram();
		if (program != 0)
		{
			GLES20.glAttachShader(program, vertexShader);
			GLES20.glAttachShader(program, pixelShader);
			GLES20.glLinkProgram(program);
			int[] linkStatus = new int[1];
			GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linkStatus, 0);
			if (linkStatus[0] != GLES20.GL_TRUE)
			{
				Log.e(TAG, "Could not link program: ");
				Log.e(TAG, GLES20.glGetProgramInfoLog(program));
				GLES20.glDeleteProgram(program);
				program = 0;
			}
		}
		return program;
	}
	
	public boolean HandleTouchEvent(MotionEvent event)
	{ 
		return m_game.TouchEvent(event);
	}
}